import { useEffect, useState } from 'react'
import useGetUserInfo from './useGetUserInfo'
import { useRequest } from 'ahooks'
import { getUserInfo } from '@/service/module/user'
import { useDispatch } from 'react-redux'
import { loginAction } from '@/store/features/user'

const useLoadUserData = () => {
  //用于记录请求是否完毕
  const [waitingUserData, setWaitingUserData] = useState(true)
  const dispatch = useDispatch()
  //加载用户信息
  const { run } = useRequest(getUserInfo, {
    manual: true,
    onSuccess(result) {
      const { username, nickname } = result
      dispatch(loginAction({ username, nickname }))
    },
    onFinally() {
      setWaitingUserData(false)
    },
  })

  const { username } = useGetUserInfo() //判断当前的登录状态
  useEffect(() => {
    if (username) {
      setWaitingUserData(false)
      return
    }
    run() //这里意味着 redux中没有用户信息 则要获取用户信息
  }, [username])

  return { waitingUserData }
}

export default useLoadUserData
